/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */

package controllers

import (
	"encoding/base64"
	"reflect"
	"strings"
	"time"
	"unsafe"

	"github.com/astaxie/beego"
)

// BaseController 基类
type BaseController struct {
	beego.Controller
}

/**
状态码
*/
const (
	CODE_OK  = 0 //表示没有错误
	CODE_ERR = 1 // 存在错误

	BASE64Table = "IJjkKLMNO567PQX12RVW3YZaDEFGbcdefghiABCHlSTUmnopqrxyz04stuvw89+/"
)

// Prepare 前期准备
func (base *BaseController) Prepare() {

}

// IsPost 是否POST提交
func (base *BaseController) IsPost() bool {
	return base.Ctx.Request.Method == "POST"
}

// GetClientIp 获取用户IP地址
func (base *BaseController) GetClientIp() string {
	s := base.Ctx.Request.RemoteAddr
	l := strings.LastIndex(s, ":")
	return s[0:l]
}

// ResJson ajax返回
func (base *BaseController) ResJson(code int, msg interface{}, data interface{}, args map[string]interface{}) {
	out := make(map[string]interface{})
	out["code"] = code
	out["msg"] = msg
	out["data"] = data
	for key, val := range args {
		out[key] = val
	}
	//beego.Date(time.Unix(time.Now(), 0), "Y-m-d H:i:s")
	//out["create_time"]  = time.Now().Format("2006-01-02 15:04:05")
	out["create_time"] = beego.Date(time.Now(), "Y-m-d H:i:s")
	base.Data["json"] = out
	base.ServeJSON()
	base.StopRun()
}

/**
 * @Description: 加密算法
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-11-05 20:56:43
 * @param {*BaseController} base
 * @return {*}
 */
func (base *BaseController) Encode(data string) string {
	content := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&data))))
	coder := base64.NewEncoding(BASE64Table)
	return coder.EncodeToString(content)
}

/**
 * @Description: 解密函数
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-11-05 20:47:01
 * @param {string} data
 * @return {*}
 */
func (base *BaseController) Decode(data string) string {
	coder := base64.NewEncoding(BASE64Table)
	result, _ := coder.DecodeString(data)
	return *(*string)(unsafe.Pointer(&result))
}
